/*
Pyxis 2.0
Copyright 2010-2011 Thomas W. Holtquist

Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at

    http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/

using System;
using System.IO;
using System.Text;
using System.Threading;

using Microsoft.SPOT;

using GHIElectronics.NETMF.Hardware;

using Skewworks.Pyxis.EXT;
using Skewworks.Pyxis.GUI.Controls;

namespace Skewworks.Pyxis.Kernel
{

    class PictureViewer
    {

        #region Variables

        private static PyxisAPI API;
        private static bool bLoaded = false;
        private static MenuItem AppMenu = null;
        private static Form frmMain = null;
        private static MenuItem mnuQuitApp;
        private static MenuItem mnuSwitchToApp;
        private static Bitmap buffer2 = null;

        private static string[] files;
        private static int iIndex;
        private static ModalMessage MM;
        private static string[] _params;
        #endregion

        #region Public Methods

        public static void Show(PyxisAPI api, string[] parameters)
        {

            API = api;
            if (API.desktop._mnu.count > 1) API.desktop._mnu.remove(1);

            if (!bLoaded)
            {
                MM = new ModalMessage("Loading Picture Viewer; Please Wait", api);
                _params = parameters;
                new Thread(CreateApp).Start();
                MM.Start();
                bLoaded = true;
            }

            // Display App
            API.desktop._mnu.add(AppMenu);
            API.ActiveForm = frmMain;

        }

        public static void Quit()
        {
            if (!bLoaded) return;

            API.desktop.mnuRun.RemoveItem(mnuSwitchToApp);
            API.desktop.mnuForce.RemoveItem(mnuQuitApp);
            if (API.desktop.mnuForce.ItemCount == 0) API.desktop.mnuForce.Enabled = false;
            if (API.desktop.mnuRun.ItemCount == 0) API.desktop.mnuRun.Enabled = false;

            API.DisplayDesktop();

            frmMain = null;
            mnuQuitApp = null;
            mnuSwitchToApp = null;

            bLoaded = false;
        }

        #endregion

        #region Private Methods

        private static void CreateApp()
        {
            Thread.Sleep(50);

            // Create Form
            frmMain = new Form(API, Colors.Black, true, true);

            Picturebox pbox = new Picturebox(null, 0, 0, frmMain.Width, frmMain.Height);
            pbox.Background = Colors.Black;
            pbox.BorderStyle = BorderStyle.BorderNone;
            pbox.ScaleMode = ScaleMode.Scale;
            pbox.tapEvent += new OnTap((object sender, point e) =>  PBoxTapped(pbox));
            frmMain.AddChild(pbox);

            // Get files
            iIndex = -1;
            if (_params != null)
            {
                files = Directory.GetFiles(Path.GetDirectoryName(_params[0]));

                try
                {
                    pbox.Image = PyxisAPI.ImageFromBytes(File.ReadAllBytes(_params[0]));
                }
                catch (Exception ex)
                {
                    ShowMessage("Cannot Display: " + ex.Message, pbox);
                }
            } else
                ShowMessage("No Image", pbox);

            // Create Application Menus
            AppMenu = new MenuItem("Picture Viewer");

            AppMenu.AddItem(new MenuItem("Open"));
            AppMenu.Item(0).tapEvent += new MenuItemTap((object sender) => OpenFile(pbox));

            AppMenu.AddItem(new MenuItem("-"));

            AppMenu.AddItem(new MenuItem("Quit"));
            AppMenu.Item(2).tapEvent += new MenuItemTap((object sender) => Quit());

            // Create Switch/Quit Menus
            mnuSwitchToApp = new MenuItem("Picture Viewer");
            mnuSwitchToApp.tapEvent += new MenuItemTap((object sender) => Show(API, null));
            mnuSwitchToApp.Tag = "Picture Viewer";
            API.desktop.mnuRun.AddItem(mnuSwitchToApp);
            API.desktop.mnuRun.Enabled = true;

            mnuQuitApp = new MenuItem("Picture Viewer");
            mnuQuitApp.tapEvent += new MenuItemTap((object sender) => Quit());
            mnuQuitApp.Tag = "Picture Viewer";
            API.desktop.mnuForce.AddItem(mnuQuitApp);
            API.desktop.mnuForce.Enabled = true;

            MM.Stop();
        }

        private static void GetNextIndex()
        {

            int i = iIndex + 1;
            bool bLooped = false;
            while (true)
            {
                if (i == files.Length)
                {
                    if (bLooped)
                    {
                        iIndex = 0;
                        return;
                    }
                    bLooped = true;
                    i = 0;
                }

                switch (Path.GetExtension(files[i]))
                {
                    case ".bmp":
                    case ".gif":
                    case ".jpg":
                    case ".jpe":
                    case ".jpeg":
                        iIndex = i;
                        return;
                }

                i++;
            }
        }

        private static void OpenFile(Picturebox pbox)
        {
            string sFile = API.OpenFile("Select Image", "", new string[] { ".bmp", ".jpg", ".jpe", ".jpeg" });
            if (sFile == string.Empty) return;
            iIndex = -1;
            files = Directory.GetFiles(Path.GetDirectoryName(sFile));
            PBoxTapped(pbox);
        }

        private static void PBoxTapped(Picturebox pbox)
        {
            if (files == null) return;

            GetNextIndex();
            try
            {
                pbox.Image = PyxisAPI.ImageFromBytes(File.ReadAllBytes(files[iIndex]));
            }
            catch (Exception ex)
            {
                ShowMessage("Cannot Display: " + ex.Message, pbox);
            }
        }

        private static void ShowMessage(string Message, Picturebox pbox)
        {
            Bitmap bmp = new Bitmap(pbox.Width, pbox.Height);
            bmp.DrawRectangle(Colors.Black, 0, 0, 0, pbox.Width, pbox.Height, 0, 0, Colors.Black, 0, 0, Colors.Black, 0, 0, 256);
            bmp.DrawTextInRect(Message, 4, 4, pbox.Width - 8, pbox.Height - 8, Bitmap.DT_AlignmentLeft, Colors.White, FontManager.Arial);
            pbox.Image = bmp;
        }

        #endregion

    }
}
